package com.xiaoman.desktop;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Objects;
import java.util.Random;

public class DesktopPet extends JFrame {
    private final JLabel petLabel;
    private Point dragStart;
    private Point windowStart;
    private boolean isDragging = false;
    private final Timer movementTimer;

    public DesktopPet() {
        // 窗口设置
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setUndecorated(true);
        setBackground(new Color(0, 0, 0, 0));
        setAlwaysOnTop(true);
        // 加载GIF动画
        ImageIcon gifIcon = new ImageIcon(Objects.requireNonNull(getClass().getResource("cat.gif")));
        petLabel = new JLabel(gifIcon);
        add(petLabel);
        pack();
        // 鼠标事件监听（保持原有拖动逻辑）
        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                isDragging = true;
                dragStart = e.getLocationOnScreen();
                windowStart = getLocation();
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                isDragging = false;
            }
        });

        addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                if (isDragging) {
                    Point current = e.getLocationOnScreen();
                    int deltaX = current.x - dragStart.x;
                    int deltaY = current.y - dragStart.y;
                    setLocation(windowStart.x + deltaX, windowStart.y + deltaY);
                }
            }
        });

        // 自动移动定时器（保持原有移动逻辑）
        movementTimer = new Timer(5000, e -> moveRandomly());
        movementTimer.start();
    }

    // 保持原有移动方法不变
    private void moveRandomly() {
        Random rand = new Random();
        int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
        int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;

        int targetX = rand.nextInt(screenWidth - 200);
        int targetY = rand.nextInt(screenHeight - 200);

        new Thread(() -> {
            try {
                Point current = getLocation();
                int steps = 50;
                for (int i = 0; i < steps; i++) {
                    int newX = current.x + (targetX - current.x) * i / steps;
                    int newY = current.y + (targetY - current.y) * i / steps;
                    setLocation(newX, newY);
                    Thread.sleep(20);
                }
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }).start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            DesktopPet pet = new DesktopPet();
            pet.setVisible(true);
        });
    }
}